package com.dries.portal.module.coupon.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.dries.portal.module.coupon.entity.Template;
import com.dries.portal.module.coupon.service.IAsyncService;
import com.dries.portal.module.coupon.service.ITemplateService;
import com.dries.portal.module.user.service.UserCacheService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.StopWatch;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

/**
 * @Description: 异步服务接口实现
 * @Author ZSY
 * @createTime 2020/7/27 15:45
 */
@Slf4j
@Data
@Service
public class AsyncServiceImpl implements IAsyncService {

    @Resource
    private UserCacheService userCacheService;
    @Resource
    private ITemplateService templateService;

    /**
     * 根据模板异步的创建优惠券码
     *
     * @param template
     */
    @Async("getAsyncExecutor")
    @Override
    public void asyncConstructCouponByTemplate(Template template) {
        StopWatch sw = StopWatch.createStarted();

        Set<String> couponCodes = buildCouponCode(template);
        userCacheService.setCouponCode(template.getId(), couponCodes);
        // 修改优惠券状态
        // template.setAvailable(1);
        templateService.saveOrUpdate(template);

        sw.stop();
        log.info("Constant CouponCode By Template Cost: {}", sw.getTime());

        // TODO 发送通知优惠券模板已经可用
    }

    /**
     * 构造优惠券码 （18位）
     * 前四位： 产品线 + 类型
     * 中间六位： 日期随机（202001）
     * 后八位： 0~9 随机数
     * @param template
     * @return
     */
    private Set<String> buildCouponCode(Template template) {
        StopWatch sw = StopWatch.createStarted();

        Set<String> result = new HashSet<>(template.getCouponCount());


        String prefix = template.getProductLine().getCode().toString()
                + template.getCategory().getCode();

        for (int i = 0; i != template.getCouponCount() ; ++i) {
            String uuid = IdUtil.simpleUUID();
            String startPre = StrUtil.sub(uuid, 0, 6);
            String endPre = StrUtil.sub(uuid, uuid.length() - 6, uuid.length());

            result.add(startPre + prefix + endPre);
        }

        while (result.size() < template.getCouponCount()) {
            String uuid = IdUtil.simpleUUID();
            String startPre = StrUtil.sub(uuid, 0, 6);
            String endPre = StrUtil.sub(uuid, uuid.length() - 6, uuid.length());
            result.add(startPre + prefix + endPre);
        }

        assert result.size() == template.getCouponCount();

        sw.stop();
        log.info("Build Coupon Code Cost: {}", sw.getTime());

        return result;

    }



}
